<template>
  <div
    class="h-screen flex flex-col bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900"
    v-loading="isLoading"
    :element-loading-text="loadingText"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div class="flex flex-1 overflow-hidden">
      <!-- 左侧面板 -->
      <div class="w-64 bg-slate-800/50 backdrop-blur-xl border-r border-cyan-500/20 flex flex-col overflow-hidden">
        <!-- Tab切换 -->
        <el-tabs v-model="leftActiveTab" :stretch="true" class="flex-1 web3-tabs">
          <!-- SQL生成 -->
          <el-tab-pane label="SQL生成" name="sql">
            <div class="p-4 flex flex-col h-full">
              <!-- 提示文字 -->
              <div class="text-cyan-400 text-sm mb-2 bg-cyan-500/10 p-2 rounded-lg border border-cyan-500/20">
                <i class="el-icon-warning mr-1"></i>
                您正在创建新文件，记得保存哦
              </div>

              <!-- SQL输入框 -->
              <div class="mb-3">
                <label class="block text-gray-300 text-sm font-medium mb-2">SQL语句</label>
                <el-input
                  v-model="sqlInput"
                  type="textarea"
                  :rows="10"
                  placeholder="请输入SQL语句"
                  class="web3-textarea"
                />
              </div>

              <!-- 数据库选择 -->
              <div class="mb-3">
                <div class="flex items-center">
                  <span class="text-gray-300 text-sm mr-2 font-medium">数据库：</span>
                  <el-select
                    v-model="selectedDatabase"
                    size="default"
                    class="flex-1 web3-select"
                  >
                    <el-option label="MySQL" value="mysql" />
<!--                    <el-option label="PostgreSQL" value="postgresql" />-->
<!--                    <el-option label="SQLite" value="sqlite" />-->
<!--                    <el-option label="Oracle" value="oracle" />-->
                  </el-select>
                </div>
              </div>

              <!-- 按钮组 -->
              <div class="flex space-x-2 mb-4">
                <el-button
                  class="flex-1 web3-button-secondary"
                  @click="generateFromSQL"
                >
                  生成
                </el-button>
                <el-button
                  class="flex-1 web3-button-primary"
                  @click="showExampleDialog = true"
                >
                  先体验一下
                </el-button>
              </div>

         
           
            </div>
          </el-tab-pane>

          <!-- AI生成 -->
          <el-tab-pane label="AI生成" name="ai">
            <div class="p-4 flex flex-col h-full">
              <!-- 提示文字 -->
              <div class="text-cyan-400 text-sm mb-2 bg-cyan-500/10 p-2 rounded-lg border border-cyan-500/20">
                <i class="el-icon-warning mr-1"></i>
                您正在创建新文件，记得保存哦
              </div>

              <!-- AI输入框 -->
              <div class="mb-3 flex-grow">
                <label class="block text-gray-300 text-sm font-medium mb-2">系统描述</label>
                <el-input
                  v-model="aiInput"
                  type="textarea"
                  :rows="12"
                  placeholder="使用AI生成需要输入你的系统详细描述，要求详细体现AI生成思维准备的示例：

学生管理系统，包含学生、课程、成绩实体
学生信息：学号、姓名、班级、联系方式
课程信息：课程编号、名称、学分
成绩关联学生和课程，记录考试成绩"
                  maxlength="500"
                  show-word-limit
                  class="web3-textarea"
                />
              </div>

              <!-- 按钮组 -->
              <div class="flex space-x-2 mb-4">
                <el-button
                  class="flex-1 web3-button-secondary"
                  @click="generateFromAI"
                >
                  生成
                </el-button>
                <el-button
                  class="flex-1 web3-button-primary"
                  @click="showExampleDialog = true"
                >
                  先体验一下
                </el-button>
              </div>

              <!-- 帮助链接 -->
              <div class="space-y-2 text-sm mb-4">
                <div class="flex items-center text-pink-400 cursor-pointer hover:text-pink-300 transition-colors">
                  <el-icon class="mr-1"><VideoPlay /></el-icon>
                  <span>视频教程</span>
                </div>
                <div class="flex items-center text-cyan-400 cursor-pointer hover:text-cyan-300 transition-colors">
                  <el-icon class="mr-1"><Document /></el-icon>
                  <span>不看吃亏使用手册</span>
                </div>
                <div class="flex items-center text-cyan-400 cursor-pointer hover:text-cyan-300 transition-colors">
                  <el-icon class="mr-1"><QuestionFilled /></el-icon>
                  <span>生成的er图没联系？点击这里解决</span>
                </div>
              </div>

              <!-- 提示文字 -->
              <div class="text-sm text-gray-400 mb-3">
                <p>若对生成的结果不满意需要指导</p>
                <p class="text-cyan-400 cursor-pointer hover:text-cyan-300 transition-colors">点击加入校园小助手</p>
              </div>

              <!-- 微信群二维码 -->
              <div class="bg-gradient-to-r from-green-500/10 to-emerald-500/10 p-3 rounded-lg border border-green-500/20 backdrop-blur-sm">
                <div class="flex items-center">
                  <div class="w-16 h-16 bg-slate-700/50 rounded-lg border border-green-500/30 flex items-center justify-center mr-3">
                    <span class="text-xs text-gray-400">二维码</span>
                  </div>
                  <div>
                    <div class="flex items-center text-green-400 font-medium text-sm mb-1">
                      <div class="w-4 h-4 bg-green-500 rounded-sm flex items-center justify-center mr-2">
                        <span class="text-white text-xs">微</span>
                      </div>
                      微信群一键
                    </div>
                    <div class="text-xs text-gray-400">
                      <span class="bg-green-500/20 text-green-400 px-2 py-1 rounded">搜</span>
                      <span class="ml-1">搜索校园小助手</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 中间画布区域 -->
      <div class="flex-1 bg-slate-800/30 backdrop-blur-sm relative overflow-hidden">
        <!-- 工具栏 -->
        <div class="absolute top-4 left-1/2 transform -translate-x-1/2 z-10">
          <div class="bg-slate-800/80 backdrop-blur-xl rounded-xl shadow-2xl border border-cyan-500/20 px-4 py-3">
            <div class="flex items-center space-x-2">
              <template v-for="(btn, idx) in toolbarButtons" :key="idx">
                <div v-if="btn.divider" class="w-px h-8 bg-gray-600/50 mx-2"></div>
                <div v-else class="flex flex-col items-center group">
                  <button 
                    @click="btn.onClick"
                    class="w-10 h-10 rounded-lg bg-slate-700/50 hover:bg-cyan-500/20 border border-slate-600/50 hover:border-cyan-500/50 flex items-center justify-center transition-all duration-200 group-hover:scale-105"
                  >
                    <el-icon class="text-gray-300 group-hover:text-cyan-400"><component :is="btn.icon" /></el-icon>
                  </button>
                  <span class="text-xs text-gray-400 mt-1 group-hover:text-cyan-400 transition-colors">{{ btn.label }}</span>
                </div>
              </template>
            </div>
          </div>
        </div>

        <!-- ER图画布 -->
        <div
          class="w-full h-full bg-gradient-to-br from-slate-900/50 to-purple-900/30 backdrop-blur-sm"
          @dragover.prevent
          @drop="onDropOnCanvas"
        >
          <div class="w-full h-full flex items-center justify-center">
            <div class="text-center">
              <div class="text-6xl text-cyan-400/30 mb-4">⚡</div>
              <h2 class="text-2xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-cyan-400 to-purple-400 mb-2">
                ER Diagram Canvas
              </h2>
              <p class="text-gray-400">
                启动可视化 qojs 实验过程，当前文件上传到后台后方法这里，但工具箱过程
              </p>
            </div>
          </div>
          <er-diagram
            ref="erDiagram"
            @export="handleExportDiagram"
            @node-selected="onNodeSelected"
          />
        </div>
      </div>
      <!-- 右侧面板 -->
      <div class="w-64 bg-slate-800/50 backdrop-blur-xl border-l border-cyan-500/20">
        <el-tabs v-model="rightActiveTab" :stretch="true" class="web3-tabs">
          <!-- 调整图形 -->
          <el-tab-pane label="调整图形" name="style">
            <div class="p-4 space-y-6">
              <!-- 配色设置 -->
              <div class="bg-slate-700/30 p-4 rounded-lg border border-slate-600/30">
                <h3 class="text-sm font-semibold text-gray-200 mb-3 flex items-center">
                  <div class="w-2 h-2 bg-cyan-400 rounded-full mr-2"></div>
                  应用节点颜色
                </h3>
                <div class="grid grid-cols-4 gap-2 mb-4">
                  <div class="w-8 h-8 bg-cyan-400 rounded-lg cursor-pointer hover:scale-110 transition-transform"></div>
                  <div class="w-8 h-8 bg-cyan-300 rounded-lg cursor-pointer hover:scale-110 transition-transform"></div>
                  <div class="w-8 h-8 bg-purple-400 rounded-lg cursor-pointer hover:scale-110 transition-transform"></div>
                  <div class="w-8 h-8 bg-purple-300 rounded-lg cursor-pointer hover:scale-110 transition-transform"></div>
                </div>
                <h3 class="text-sm font-semibold text-gray-200 mb-3 flex items-center">
                  <div class="w-2 h-2 bg-purple-400 rounded-full mr-2"></div>
                  应用线条颜色
                </h3>
                <div class="space-y-3">
                  <div class="flex items-center justify-between">
                    <span class="text-sm text-gray-300">节点颜色</span>
                    <el-color-picker
                      v-model="nodeColor"
                      show-alpha
                      size="small"
                      @change="updateNodeColor"
                      class="web3-color-picker"
                    />
                  </div>
                  <div class="flex items-center justify-between">
                    <span class="text-sm text-gray-300">线条颜色</span>
                    <el-color-picker
                      v-model="lineColor"
                      show-alpha
                      size="small"
                      @change="updateLineColor"
                      class="web3-color-picker"
                    />
                  </div>
                </div>
              </div>

              <!-- 布局设置 -->
              <div class="bg-slate-700/30 p-4 rounded-lg border border-slate-600/30">
                <h3 class="text-sm font-semibold text-gray-200 mb-3 flex items-center">
                  <div class="w-2 h-2 bg-pink-400 rounded-full mr-2"></div>
                  布局设置
                </h3>
                <div class="flex items-center justify-between">
                  <span class="text-sm text-gray-300">布局类型</span>
                  <el-select
                    v-model="layoutType"
                    size="small"
                    style="width: 120px"
                    @change="setLayoutType"
                    class="web3-select"
                  >
                    <el-option label="经典布局" value="classic" />
                    <el-option label="树状布局" value="tree" />
                    <el-option label="星芒布局" value="star" />
                  </el-select>
                </div>
              </div>

              <!-- 文字设置 -->
              <div class="bg-slate-700/30 p-4 rounded-lg border border-slate-600/30">
                <h3 class="text-sm font-semibold text-gray-200 mb-3">文字设置</h3>
                <div class="space-y-3">
                  <div class="flex items-center justify-between">
                    <span class="text-sm text-gray-300">文字大小</span>
                    <el-input
                      v-model="fontSize"
                      size="small"
                      style="width: 60px"
                      type="number"
                      :min="12"
                      :max="24"
                      class="web3-input"
                    />
                  </div>
                  <div class="flex items-center justify-between">
                    <span class="text-sm text-gray-300">字体样式</span>
                    <el-select
                      v-model="fontFamily"
                      size="small"
                      style="width: 80px"
                      class="web3-select"
                    >
                      <el-option label="宋体" value="SimSun" />
                      <el-option label="微软雅黑" value="Microsoft YaHei" />
                      <el-option label="Arial" value="Arial" />
                    </el-select>
                  </div>
                  <el-button
                    size="small"
                    class="w-full web3-button-gradient"
                    @click="showAddFontDialog = true"
                  >
                    <el-icon class="mr-1"><Download /></el-icon>
                    添加字体
                  </el-button>
                </div>
              </div>

              <!-- 边框密度设置 -->
              <!--              <div>-->
              <!--                <h3 class="text-sm font-medium text-gray-700 mb-3" style="font-size: 14px;font-weight: 600">-->
              <!--                  边框密度设置-->
              <!--                </h3>-->
              <!--                <div class="space-y-2">-->
              <!--                  <el-radio-group v-model="borderDensity" size="small">-->
              <!--                    <div class="flex flex-col space-y-2">-->
              <!--                      <el-radio label="center">居中显示</el-radio>-->
              <!--                      <el-radio label="top">上方显示</el-radio>-->
              <!--                    </div>-->
              <!--                  </el-radio-group>-->
              <!--                </div>-->
              <!--              </div>-->

              <!-- 图形工具 -->
              <div class="bg-slate-700/30 p-4 rounded-lg border border-slate-600/30">
                <h3 class="text-sm font-semibold text-gray-200 mb-3">图形工具</h3>
                <div class="flex justify-between items-center">
                  <div class="grid grid-cols-2 gap-2 flex-1">
                    <el-button
                      size="small"
                      draggable="true"
                      @dragstart="onDragStart('entity', $event)"
                      class="web3-button-tool"
                    >矩形</el-button>
                    <el-button
                      size="small"
                      draggable="true"
                      @dragstart="onDragStart('attribute', $event)"
                      class="web3-button-tool"
                    >椭圆</el-button>
                  </div>
                  <span class="text-xs text-gray-400 ml-2">指向到画布使用</span>
                </div>
              </div>

              <!-- 总表和单表 -->
              <div class="bg-slate-700/30 p-4 rounded-lg border border-slate-600/30">
                <h3 class="text-sm font-semibold text-gray-200 mb-3">总表和单表</h3>
                <p class="text-xs text-gray-400 mb-3">选择特定表格后可显示关系表关系</p>
                <div class="space-y-3">
                  <div class="flex items-center justify-between">
                    <el-button
                      :class="selectedEntity === 'all' ? 'web3-button-active' : 'web3-button-inactive'"
                      size="small"
                      @click="handleEntitySelect('all')"
                    >总表</el-button>
                    <div class="flex items-center">
                      <span class="text-sm text-gray-300 mr-2">呈现关系</span>
                      <el-switch 
                        v-model="showRelations" 
                        size="small"
                        active-color="#06b6d4"
                        inactive-color="#374151"
                      />
                    </div>
                  </div>
                  <div class="grid grid-cols-2 gap-2">
                    <div
                      v-for="entity in entityList"
                      :key="entity"
                      :class="[
                        selectedEntity === entity
                          ? 'bg-gradient-to-r from-purple-500 to-pink-500 text-white shadow-lg'
                          : 'bg-slate-600/50 text-purple-300 hover:bg-slate-600/70',
                        'p-2 rounded-lg text-center text-sm cursor-pointer transition-all duration-200 border border-purple-500/20'
                      ]"
                      @click="handleEntitySelect(entity)"
                    >
                      {{ entity }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 节点修改 -->
          <el-tab-pane label="节点修改" name="node">
            <div class="p-4 space-y-6">
              <!-- 修改当前节点信息 -->
              <div class="bg-slate-700/30 p-4 rounded-lg border border-slate-600/30">
                <h3 class="text-lg font-semibold text-gray-200 mb-4">修改当前节点信息</h3>
                <div class="space-y-3">
                  <div>
                    <label class="block text-sm text-gray-300 mb-2 font-medium">实体名称：</label>
                    <div class="flex items-center space-x-2">
                      <el-input
                        v-model="selectedNodeName"
                        size="large"
                        class="flex-1 web3-input"
                        placeholder="请输入实体名称"
                      />
                      <button 
                        @click="toggleUnderline"
                        class="w-10 h-10 rounded-lg bg-slate-600/50 hover:bg-cyan-500/20 border border-slate-500/50 hover:border-cyan-500/50 flex items-center justify-center transition-all"
                      >
                        <el-icon class="text-gray-300 hover:text-cyan-400"><UnderlineIcon /></el-icon>
                      </button>
                      <button 
                        @click="handleDeleteNode"
                        class="w-10 h-10 rounded-lg bg-slate-600/50 hover:bg-red-500/20 border border-slate-500/50 hover:border-red-500/50 flex items-center justify-center transition-all"
                      >
                        <el-icon class="text-gray-300 hover:text-red-400"><Delete /></el-icon>
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 给实体之间添加线 -->
              <div
                v-if="selectedNode && (selectedNode.category === 'Entity' || selectedNode.category === 'Relationship')"
                class="bg-slate-700/30 p-4 rounded-lg border border-slate-600/30"
              >
                <h3 class="text-lg font-semibold text-gray-200 mb-4">给实体之间添加线</h3>
                <div class="space-y-3">
                  <div class="flex items-center space-x-2">
                    <el-input
                      v-model="relationName"
                      size="large"
                      placeholder="请输入关系名称"
                      class="web3-input"
                    />
                    <el-select
                      v-model="selectedEntityForRelation"
                      size="large"
                      placeholder="选择实体"
                      class="web3-select"
                    >
                      <el-option
                        v-for="entity in availableEntitiesForRelation"
                        :key="entity"
                        :label="entity"
                        :value="entity"
                      />
                    </el-select>
                  </div>
                  <el-button
                    size="large"
                    class="w-full web3-button-secondary"
                    @click="handleAddRelationshipLine"
                  >
                    添加关系
                  </el-button>
                </div>
              </div>

              <!-- 给当前选择的添加线 -->
              <div v-if="selectedNode" class="bg-slate-700/30 p-4 rounded-lg border border-slate-600/30">
                <h3 class="text-lg font-semibold text-gray-200 mb-4">给当前选择的添加线</h3>
                <div class="space-y-3">
                  <div>
                    <label class="block text-sm text-gray-300 mb-2 font-medium">新增类型：</label>
                    <el-select
                      v-model="newConnectionType"
                      size="large"
                      class="w-full web3-select"
                    >
                      <el-option label="属性" value="attribute" />
                      <el-option label="关系" value="relationship" />
                      <el-option label="实体" value="entity" />
                    </el-select>
                  </div>
                  <div>
                    <el-input
                      v-model="newConnectionName"
                      placeholder="请输入名称"
                      size="large"
                      class="web3-input"
                    />
                  </div>
                  <el-button
                    size="large"
                    class="w-full web3-button-primary"
                    @click="handleAddConnection"
                  >
                    添加
                  </el-button>
                </div>
              </div>

              <!-- 提示信息 -->
              <div class="text-sm text-gray-400 bg-yellow-500/10 p-4 rounded-lg border border-yellow-500/20">
                <div class="flex items-center">
                  <div class="w-2 h-2 bg-yellow-400 rounded-full mr-2"></div>
                  如果文字超出或者图形太大，记得点击右上角的重新渲染
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 测试例子弹窗 -->
    <el-dialog
      v-model="showExampleDialog"
      title="测试例子"
      width="600px"
      :before-close="handleExampleDialogClose"
      class="web3-dialog"
    >
      <div class="bg-slate-800/50 p-4 rounded-lg border border-slate-600/30">
        <pre class="text-sm text-gray-300 whitespace-pre-wrap">{{ exampleSQL }}</pre>
      </div>
      <template #footer>
        <div class="flex justify-end space-x-3">
          <el-button @click="showExampleDialog = false" class="web3-button-secondary">取消</el-button>
          <el-button @click="useExample" class="web3-button-primary">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="showAddFontDialog"
      title="添加自定义字体"
      width="400px"
      :close-on-click-modal="false"
      class="web3-dialog"
    >
      <el-form>
        <el-form-item label="字体名称">
          <el-input v-model="addFontForm.name" placeholder="请输入字体名称" class="web3-input" />
        </el-form-item>
        <el-form-item label="字体文件">
          <el-upload
            :show-file-list="false"
            :auto-upload="false"
            :before-upload="handleFontUpload"
            accept=".ttf,.woff,.otf"
          >
            <el-button size="small" class="web3-button-secondary">
              <el-icon class="mr-1"><Upload /></el-icon>
              选择字体文件
            </el-button>
          </el-upload>
          <div class="text-xs text-gray-400 mt-1">
            支持 .ttf、.woff、.otf 格式
          </div>
          <div v-if="addFontForm.fileName" class="text-xs text-green-400 mt-1">
            已选择：{{ addFontForm.fileName }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddFontDialog = false" class="web3-button-secondary">取消</el-button>
        <el-button @click="handleAddFont" class="web3-button-primary">添加并应用</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  computed,
  watch,
  onUnmounted
} from "vue";
import * as go from "gojs";
import SqlEditor from "./components/SqlEditor.vue";
import ErDiagram from "./components/ErDiagram.vue";
import ExportDialog from "./components/ExportDialog.vue";
import { sqlParse } from "@/api/tools";
import {
  Warning,
  Document,
  Download,
  VideoPlay,
  QuestionFilled,
  ZoomIn,
  ZoomOut,
  Edit,
  Delete,
  Back,
  Right,
  FullScreen,
  Folder,
  View,
  DocumentCopy,
  Upload,
  Crop,
  RefreshLeft
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { fixMySqlForParser, removeFkComments } from "./utils/sqlParser";
// import { parseSqlToDiagramTables, DiagramTable } from './utils/sqlAstParser';
import { parseSQLToERStructureFromAst } from "./utils/parseSqlToERStructureFromAst";
import UnderlineIcon from "@/assets/svg/UnderlineIcon.svg?component";

// 清理SQL语句，移除不兼容的语法
const cleanSqlForParser = (sql: string): string => {
  let cleanedSql = sql;
  
  console.log("原始SQL:", sql);
  
  // 移除列级别的COMMENT
  cleanedSql = cleanedSql.replace(/COMMENT\s+['"`][^'"`]*['"`]/gi, '');
  console.log("移除列COMMENT后:", cleanedSql);
  
  // 移除表级别的COMMENT
  cleanedSql = cleanedSql.replace(/\)\s*COMMENT\s+['"`][^'"`]*['"`]/gi, ')');
  console.log("移除表COMMENT后:", cleanedSql);
  
  // 移除AUTO_INCREMENT
  cleanedSql = cleanedSql.replace(/\s+AUTO_INCREMENT\s*\d*/gi, '');
  console.log("移除AUTO_INCREMENT后:", cleanedSql);
  
  // 移除ENGINE和CHARSET设置
  cleanedSql = cleanedSql.replace(/\s+ENGINE\s*=\s*\w+/gi, '');
  cleanedSql = cleanedSql.replace(/\s+CHARSET\s*=\s*\w+/gi, '');
  cleanedSql = cleanedSql.replace(/\s+COLLATE\s*=\s*\w+/gi, '');
  console.log("移除ENGINE/CHARSET后:", cleanedSql);
  
  // 移除DEFAULT CHARSET
  cleanedSql = cleanedSql.replace(/\s+DEFAULT\s+CHARSET\s*=\s*\w+/gi, '');
  console.log("移除DEFAULT CHARSET后:", cleanedSql);
  
  // 移除ON UPDATE和ON DELETE约束
  cleanedSql = cleanedSql.replace(/\s+ON\s+UPDATE\s+\w+/gi, '');
  cleanedSql = cleanedSql.replace(/\s+ON\s+DELETE\s+\w+/gi, '');
  console.log("移除ON UPDATE/DELETE后:", cleanedSql);
  
  // 移除UNIQUE约束
  cleanedSql = cleanedSql.replace(/\s+UNIQUE\s+KEY\s*$$[^)]+$$/gi, '');
  cleanedSql = cleanedSql.replace(/\s+UNIQUE\s*$$[^)]+$$/gi, '');
  console.log("移除UNIQUE约束后:", cleanedSql);
  
  // 移除INDEX约束
  cleanedSql = cleanedSql.replace(/\s+KEY\s+`?\w+`?\s*$$[^)]+$$/gi, '');
  cleanedSql = cleanedSql.replace(/\s+INDEX\s+`?\w+`?\s*$$[^)]+$$/gi, '');
  console.log("移除INDEX约束后:", cleanedSql);
  
  // 清理多余的空格和换行
  cleanedSql = cleanedSql.replace(/\s+/g, ' ').trim();
  console.log("清理空格后:", cleanedSql);
  
  // 确保语句以分号结尾
  if (!cleanedSql.endsWith(';')) {
    cleanedSql += ';';
  }
  
  console.log("最终清理后的SQL:", cleanedSql);
  return cleanedSql;
};

// SQL格式校验函数
const validateSqlFormat = (sql: string) => {
  const trimmedSql = sql.trim();
  
  // 基本检查
  if (!trimmedSql) {
    return {
      isValid: false,
      errorMessage: "SQL语句不能为空"
    };
  }

  // 检查是否包含CREATE TABLE语句
  if (!/CREATE\s+TABLE/i.test(trimmedSql)) {
    return {
      isValid: false,
      errorMessage: "SQL语句必须包含CREATE TABLE语句"
    };
  }

  // 检查括号匹配
  const openBrackets = (trimmedSql.match(/\(/g) || []).length;
  const closeBrackets = (trimmedSql.match(/\)/g) || []).length;
  if (openBrackets !== closeBrackets) {
    return {
      isValid: false,
      errorMessage: "SQL语句中括号不匹配"
    };
  }

  // 检查分号
  if (!trimmedSql.endsWith(';')) {
    return {
      isValid: false,
      errorMessage: "SQL语句必须以分号结尾"
    };
  }

  // 检查基本的CREATE TABLE语法
  const createTableRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?(\w+)`?\s*\(/gi;
  if (!createTableRegex.test(trimmedSql)) {
    return {
      isValid: false,
      errorMessage: "CREATE TABLE语法格式不正确"
    };
  }

  // 检查是否包含列定义
  if (!/^\s*CREATE\s+TABLE.*$$[\s\S]*$$/i.test(trimmedSql)) {
    return {
      isValid: false,
      errorMessage: "CREATE TABLE语句缺少列定义"
    };
  }

  // 检查列定义格式
  const columnDefinitions = trimmedSql.match(/`?\w+`?\s+\w+/gi);
  if (!columnDefinitions || columnDefinitions.length === 0) {
    return {
      isValid: false,
      errorMessage: "未找到有效的列定义"
    };
  }

  // 检查是否有语法错误（常见错误模式）
  const commonErrors = [
    {
      pattern: /,\s*,/g,
      message: "SQL语句中存在连续的逗号"
    },
    {
      pattern: /\(\s*,/g,
      message: "列定义开始处不能有逗号"
    },
    {
      pattern: /,\s*\)/g,
      message: "列定义结束处不能有逗号"
    },
    {
      pattern: /;\s*;/g,
      message: "SQL语句中存在多个连续分号"
    }
  ];

  for (const error of commonErrors) {
    if (error.pattern.test(trimmedSql)) {
      return {
        isValid: false,
        errorMessage: error.message
      };
    }
  }

  // 检查数据类型是否合理
  const dataTypes = ['INT', 'VARCHAR', 'CHAR', 'TEXT', 'DATETIME', 'DATE', 'TIMESTAMP', 'DECIMAL', 'FLOAT', 'DOUBLE', 'BOOLEAN', 'BLOB'];
  const hasValidDataType = dataTypes.some(type => 
    new RegExp(`\\b${type}\\b`, 'i').test(trimmedSql)
  );
  
  if (!hasValidDataType) {
    return {
      isValid: false,
      errorMessage: "未找到有效的MySQL数据类型"
    };
  }

  return {
    isValid: true,
    errorMessage: ""
  };
};
// Tab状态
const leftActiveTab = ref("sql");
const rightActiveTab = ref("style");
const selectedNode = ref(null);
const onNodeSelected = node => {
  selectedNode.value = node;
  rightActiveTab.value = "node";
  selectedNodeName.value = node.name;
};
// 下划线切换
const toggleUnderline = () => {
  if (!selectedNode.value) return;
  erDiagram.value?.setNodeUnderline(
    selectedNode.value.key,
    !selectedNode.value.underline
  );
  // 刷新本地selectedNode
  selectedNode.value = erDiagram.value?.getNodeByKey(selectedNode.value.key);
};
const handleDeleteNode = () => {
  if (!selectedNode.value) return;
  erDiagram.value?.deleteNode(selectedNode.value.key);
  selectedNode.value = null;
};
// loading
const isLoading = ref(false);
const loadingText = ref("");
// 给实体之间添加线
const relationName = ref("");
const selectedEntityForRelation = ref("");
// “给实体之间添加线”区域显示条件
// <div v-if="selectedNode && (selectedNode.category === 'Entity' || selectedNode.category === 'Relationship')">
// 下拉数据
const availableEntitiesForRelation = computed(() => {
  return erDiagram.value?.getEntityListWithRelationships
    ? erDiagram.value
        .getEntityListWithRelationships()
        .filter(e => e !== selectedNode.value?.key)
    : [];
});
const handleAddRelationshipLine = () => {
  if (
    !selectedNode.value ||
    !selectedEntityForRelation.value ||
    !relationName.value
  )
    return;
  erDiagram.value?.addRelationshipLine(
    selectedNode.value.key,
    selectedEntityForRelation.value,
    relationName.value
  );
  relationName.value = "";
  selectedEntityForRelation.value = "";
};
// 给当前选择的添加线
const handleAddConnection = () => {
  if (
    !selectedNode.value ||
    !newConnectionType.value ||
    !newConnectionName.value
  )
    return;
  erDiagram.value?.addConnectionToNode(
    newConnectionType.value,
    newConnectionName.value,
    selectedNode.value.key
  );
  newConnectionName.value = "";
};

// 输入内容
const sqlInput = ref("");
const aiInput = ref("");
const selectedDatabase = ref("mysql");

// 画布相关
const erDiagram = ref(null);

const canvasContainer = ref();
const canvasWidth = ref(1200);
const canvasHeight = ref(800);
const zoomLevel = ref(100);

// 样式设置
const fontSize = ref(16);
const fontFamily = ref("宋体");
const borderDensity = ref("center");
const nodeColor = ref("#000000");
const lineColor = ref("#000000");
const autoUpdate = ref(true);

// 节点修改
const selectedNodeName = ref("实体4");
const newConnectionType = ref("属性");
const newConnectionName = ref("");
const entityConnection = reactive({
  from: "",
  type: "one-to-one"
});

// 弹窗控制
const showExampleDialog = ref(false);
const showAddFontDialog = ref(false);
const addFontForm = reactive({
  name: "",
  file: null as File | null,
  fileName: ""
});

// 示例SQL
const exampleSQL = `CREATE TABLE Students (
    id INT PRIMARY KEY COMMENT '学号',
    name VARCHAR(100) COMMENT '姓名',
    age INT COMMENT '年龄',
    email VARCHAR(100) COMMENT '邮箱'
) COMMENT '学生表';

CREATE TABLE Courses (
    id INT PRIMARY KEY COMMENT '课程ID',
    course_name VARCHAR(100) COMMENT '课程名',
    credits INT COMMENT '学分'
) COMMENT '课程表';

CREATE TABLE Enrollments (
    student_id INT COMMENT '关联学生',
    course_id INT COMMENT '关联课程',
    enrollment_date DATE COMMENT '注册日期',
    PRIMARY KEY (student_id, course_id),
    FOREIGN KEY (student_id) REFERENCES Students(id),
    FOREIGN KEY (course_id) REFERENCES Courses(id)
) COMMENT '选课表';`;

// ER图数据
const entities = ref([
  { id: 1, name: "属性1", x: 300, y: 150, radius: 30, selected: false },
  { id: 2, name: "属性3", x: 200, y: 200, radius: 30, selected: false },
  { id: 3, name: "属性2", x: 150, y: 300, radius: 30, selected: false },
  { id: 4, name: "属性7", x: 500, y: 250, radius: 30, selected: false },
  { id: 5, name: "属性2", x: 400, y: 350, radius: 30, selected: false },
  { id: 6, name: "属性1", x: 300, y: 450, radius: 30, selected: false },
  { id: 7, name: "属性3", x: 250, y: 550, radius: 30, selected: false },
  { id: 8, name: "属性5", x: 200, y: 650, radius: 30, selected: false },
  { id: 9, name: "属性9", x: 600, y: 400, radius: 30, selected: false },
  { id: 10, name: "属性8", x: 550, y: 500, radius: 30, selected: false },
  { id: 11, name: "属性4", x: 350, y: 700, radius: 30, selected: false },
  { id: 12, name: "属性6", x: 450, y: 750, radius: 30, selected: false }
]);

const relationships = ref([
  {
    id: 1,
    name: "实体3",
    x: 250,
    y: 250,
    width: 60,
    height: 30,
    selected: false
  },
  {
    id: 2,
    name: "实体4",
    x: 450,
    y: 400,
    width: 60,
    height: 30,
    selected: false
  },
  {
    id: 3,
    name: "实体1",
    x: 300,
    y: 500,
    width: 60,
    height: 30,
    selected: false
  },
  {
    id: 4,
    name: "实体2",
    x: 400,
    y: 650,
    width: 60,
    height: 30,
    selected: false
  }
]);

const connections = ref([
  { id: 1, x1: 300, y1: 150, x2: 250, y2: 250, label: "1" },
  { id: 2, x1: 200, y1: 200, x2: 250, y2: 250, label: "" },
  { id: 3, x1: 250, y1: 250, x2: 150, y2: 300, label: "" },
  { id: 4, x1: 500, y1: 250, x2: 450, y2: 400, label: "N" },
  { id: 5, x1: 450, y1: 400, x2: 600, y2: 400, label: "" },
  { id: 6, x1: 450, y1: 400, x2: 300, y2: 500, label: "" },
  { id: 7, x1: 300, y1: 450, x2: 300, y2: 500, label: "" },
  { id: 8, x1: 300, y1: 500, x2: 250, y2: 550, label: "N" },
  { id: 9, x1: 400, y1: 650, x2: 200, y2: 650, label: "" },
  { id: 10, x1: 400, y1: 650, x2: 350, y2: 700, label: "" },
  { id: 11, x1: 400, y1: 650, x2: 450, y2: 750, label: "" }
]);

// 1. 定义SSE逻辑
const sqlContent = ref<string>("");
let eventSource: EventSource | null = null;
let backtickCount = 0; // 添加计数器来跟踪\`\`\`的数量

const startSSE = (desc: string) => {
  sqlContent.value = "";
  backtickCount = 0; // 重置计数器
  isLoading.value = true;
  loadingText.value = "AI生成中，请耐心等待....";
  if (eventSource) eventSource.close();

  const baseUrl = import.meta.env.VITE_API_BASE;
   const url = `${baseUrl}/tools/api/generate?desc=${encodeURIComponent(desc)}`;
  eventSource = new EventSource(url);

  eventSource.onmessage = (event: MessageEvent) => {
    let line = event.data;
    // ...数据处理
    // 数据处理逻辑
    if (line.startsWith("data: ")) {
      line = line.substring(6);
    }
    if (line.startsWith("sql")) {
      line = line.substring(6);
    }
    
    // 检查是否是\`\`\`标记
    if (line.includes("\`\`\`")) {
      backtickCount++;
      console.log("收到第" + backtickCount + "个\`\`\`标记");
      
      // 当收到第二个\`\`\`时，认为推送结束
      if (backtickCount >= 2) {
        console.log("收到第二个\`\`\`，推送结束");
        eventSource?.close();
        isLoading.value = false;
        console.log("最终SQL内容:", sqlContent.value);
        handleParseSql(sqlContent.value);
        return;
      }
      
      // 过滤掉\`\`\`标记，但保留其他内容
      line = line.replace(/\`\`\`/g, '');
    }

    console.log("sqlContent:", sqlContent.value);
    
    // 移除原来的[DONE]判断
    // if (line === "[DONE]") {
    //   console.log("[DONE][DONE][DONE]");
    //   eventSource?.close();
    //   isLoading.value = false;
    //   console.log(sqlContent.value);
    //   handleParseSql(sqlContent.value);
    //   return;
    // }
    
    // 拼接内容（如果需要显示可以取消注释）
    sqlContent.value += line;
  };

  eventSource.onerror = () => {
    isLoading.value = false;
    eventSource?.close();
  };
};

// 2. 组件卸载时自动清理
const stopSSE = () => {
  if (eventSource) {
    eventSource.close();
    eventSource = null;
    console.log("SSE连接已关闭");
  }
};
onUnmounted(stopSSE); // 关键点：注册卸载钩子

// 3. 组件方法
const generateSQL = () => {
  startSSE("创建用户表，包含id、name和email字段");
};

// 拖拽相关
const isDragging = ref(false);
const dragTarget = ref(null);
const dragOffset = reactive({ x: 0, y: 0 });

// 工具栏按钮配置
const toolbarButtons = [
  { icon: Back, label: "撤销", onClick: () => erDiagram.value?.undo() },
  { icon: Right, label: "前进", onClick: () => erDiagram.value?.redo() },
  { divider: true },
  {
    icon: FullScreen,
    label: "全屏",
    onClick: () => erDiagram.value?.fullscreen()
  },
  {
    icon: Folder,
    label: "保存",
    onClick: () => erDiagram.value?.handleSave("save")
  },
  {
    icon: View,
    label: "隐藏",
    onClick: () => erDiagram.value?.toggleAttributes()
  },
  {
    icon: DocumentCopy,
    label: "另存",
    onClick: () => erDiagram.value?.handleSave("saveAs")
  },
  { icon: Upload, label: "导出", onClick: null }, // 用下拉菜单替代
  { divider: true },
  { icon: Crop, label: "缩放", onClick: () => erDiagram.value?.fitToScreen() },
  { icon: RefreshLeft, label: "刷新", onClick: () => resetView() }
  // { icon: Download, label: "下载", onClick: () => erDiagram.value?.downloadImage() }
];

// 工具栏方法
const undo = () => {
  ElMessage.info("撤销操作");
};

const redo = () => {
  ElMessage.info("重做操作");
};

const fullscreen = () => {
  ElMessage.info("全屏模式");
};

const hidePanel = () => {
  ElMessage.info("隐藏面板");
};

const saveAs = () => {
  ElMessage.info("另存为");
};

const downloadImage = () => {
  ElMessage.info("下载图片");
};

// 1. 配色设置
const updateNodeColor = () => {
  erDiagram.value?.setNodeColor(nodeColor.value);
  ElMessage.success("节点颜色已更新");
};
const updateLineColor = () => {
  erDiagram.value?.setLineColor(lineColor.value);
  ElMessage.success("线条颜色已更新");
};
// 2. 布局设置
const layoutType = ref("classic");
const setLayoutType = (type: string) => {
  erDiagram.value?.setLayout(type);
  ElMessage.success(
    `切换为${type === "classic" ? "经典布局" : type === "tree" ? "树状布局" : "星芒布局"}`
  );
};
// 4. 图形工具
const addMode = ref(null as null | "entity" | "attribute");
const handleAddNodeClick = (type: "entity" | "attribute") => {
  addMode.value = type;
  ElMessage.info(
    `请在画布上点击以添加${type === "entity" ? "矩形实体" : "椭圆属性"}`
  );
};
const handleCanvasAddNode = (e: MouseEvent) => {
  if (!addMode.value) return;
  const diagramDiv = document.querySelector(".diagram-container");
  if (!diagramDiv) return;
  const rect = diagramDiv.getBoundingClientRect();
  const pos = { x: e.clientX - rect.left, y: e.clientY - rect.top };
  erDiagram.value?.addNode(addMode.value, pos);
  addMode.value = null;
};
// 5. 总表和单表
const selectedEntity = ref("all");
const entityList = ref(["实体1", "实体2", "实体3", "实体4"]); // 实际应从ER数据动态获取
const handleEntitySelect = (entity: string) => {
  selectedEntity.value = entity;
  erDiagram.value?.filterEntities(entity);
};
// 6. 呈现联系
const showRelations = ref(true);
watch(showRelations, val => {
  erDiagram.value?.toggleRelations(val);
});
// 3. 边框密度设置
watch(borderDensity, val => {
  erDiagram.value?.setLinkLabelPosition(val);
});

// 方法
const generateFromSQL = () => {
  if (!sqlInput.value.trim()) {
    ElMessage.warning("请输入SQL语句");
    return;
  }
  ElMessage.success("正在生成ER图...");
  // 这里可以实现SQL解析和ER图生成逻辑
  handleParseSql(sqlInput.value);
};
const cleanSqlInput = raw => {
  return raw
    .replace(/[\r\n]+/g, "\n") // 标准换行
    .replace(/\s+;/g, ";") // 清理语句后多余空格
    .replace(/;+$/, ";") // 保证结尾只有一个分号
    .trim();
};
const handleParseSql = async sql => {
  console.log(sql);
  if (!sql.trim()) {
    ElMessage.warning("请输入SQL建表语句");
    return;
  }

  // SQL格式校验
  const sqlValidation = validateSqlFormat(sql);
  if (!sqlValidation.isValid) {
    ElMessage.error(sqlValidation.errorMessage);
    return;
  }

  try {
    // 清理SQL语句，移除不兼容的语法
    const cleanedSql = cleanSqlForParser(sql);
    console.log("清理后的SQL:", cleanedSql);
    
    // 先尝试后端解析
    sqlParse({ sql }).then((res: any) => {
      console.log("后端解析结果:", res);
      let resultData = res.tables;
      
      // 处理res.tables数据，修改columns数组中元素的键名
      if (resultData && resultData.length > 0) {
        resultData = resultData.map(table => {
          if (table.columns && Array.isArray(table.columns)) {
            table.columns = table.columns.map(column => {
              const newColumn = { ...column };
              // 将columnName改为name
              if (newColumn.columnName !== undefined) {
                newColumn.name = newColumn.columnName;
                delete newColumn.columnName;
              }
              // 将columnComment改为comment
              if (newColumn.columnComment !== undefined) {
                newColumn.comment = newColumn.columnComment;
                delete newColumn.columnComment;
              }
              return newColumn;
            });
          }
          return table;
        });
      }
      
      if (resultData && resultData.length > 0) {
        erDiagram.value.updateDiagram(resultData);
        ElMessage.success("ER图生成成功");
        // 同步右侧颜色选择器和实体列表
        nextTick(() => {
          nodeColor.value = erDiagram.value?.getCurrentNodeColor() || "#1890ff";
          lineColor.value = erDiagram.value?.getCurrentLineColor() || "#1890ff";
          entityList.value = erDiagram.value?.getEntityList() || [];
        });
      } else {
        ElMessage.warning("后端解析未返回有效数据");
      }
    }).catch((error) => {
      console.error("后端解析失败:", error);
      ElMessage.error("SQL解析失败，请检查语法");
    });
    
    // 尝试AST解析（作为备用）
    try {
      console.log("开始AST解析...");
      const tables = parseSQLToERStructureFromAst(cleanedSql);
      console.log("AST解析成功，结果:", JSON.stringify(tables, null, 2));
      // AST解析成功，但主要使用后端解析结果
    } catch (astError) {
      console.error("AST解析失败:", astError);
      console.log("AST解析失败，但后端解析可能成功");
    }

    // if (tables) {
    // erDiagram.value.updateDiagram(tables);
    // let resultData = [
    //   {
    //     tableName: "Students",
    //     comment: "",
    //     columns: [
    //       {
    //         name: "id",
    //         comment: "学号"
    //       },
    //       {
    //         name: "name",
    //         comment: "姓名"
    //       },
    //       {
    //         name: "age",
    //         comment: "年龄"
    //       },
    //       {
    //         name: "email",
    //         comment: "邮箱"
    //       },
    //       {
    //         name: "department_id",
    //         comment: "所属院系"
    //       }
    //     ],
    //     primaryKeys: [],
    //     foreignKeys: [
    //       {
    //         column: "department_id",
    //         referenceTable: "Departments",
    //         referenceColumn: "id",
    //         comment: "所属院系外键"
    //       }
    //     ]
    //   },
    //   {
    //     tableName: "Courses",
    //     comment: "",
    //     columns: [
    //       {
    //         name: "id",
    //         comment: "课程ID"
    //       },
    //       {
    //         name: "course_name",
    //         comment: "课程名"
    //       },
    //       {
    //         name: "credits",
    //         comment: "学分"
    //       },
    //       {
    //         name: "teacher_id",
    //         comment: "授课教师"
    //       },
    //       {
    //         name: "department_id",
    //         comment: "开设院系"
    //       }
    //     ],
    //     primaryKeys: [],
    //     foreignKeys: [
    //       {
    //         column: "teacher_id",
    //         referenceTable: "Teachers",
    //         referenceColumn: "id",
    //         comment: "授课教师外键"
    //       },
    //       {
    //         column: "department_id",
    //         referenceTable: "Departments",
    //         referenceColumn: "id",
    //         comment: "开设院系外键"
    //       }
    //     ]
    //   },
    //   {
    //     tableName: "Enrollments",
    //     comment: "",
    //     columns: [
    //       {
    //         name: "student_id",
    //         comment: "关联学生"
    //       },
    //       {
    //         name: "course_id",
    //         comment: "关联课程"
    //       },
    //       {
    //         name: "enrollment_date",
    //         comment: "注册日期"
    //       }
    //     ],
    //     primaryKeys: ["student_id", "course_id"],
    //     foreignKeys: [
    //       {
    //         column: "student_id",
    //         referenceTable: "STUDENTS",
    //         referenceColumn: "ID",
    //         comment: "外键"
    //       },
    //       {
    //         column: "course_id",
    //         referenceTable: "COURSES",
    //         referenceColumn: "ID",
    //         comment: "外键"
    //       },
    //       {
    //         column: "student_id",
    //         referenceTable: "Students",
    //         referenceColumn: "id",
    //         comment: "推测外键"
    //       },
    //       {
    //         column: "course_id",
    //         referenceTable: "Courses",
    //         referenceColumn: "id",
    //         comment: "推测外键"
    //       }
    //     ]
    //   },
    //   {
    //     tableName: "Teachers",
    //     comment: "教师信息表",
    //     columns: [
    //       {
    //         name: "id",
    //         comment: "教师ID"
    //       },
    //       {
    //         name: "name",
    //         comment: "教师姓名"
    //       },
    //       {
    //         name: "title",
    //         comment: "职称"
    //       },
    //       {
    //         name: "department_id",
    //         comment: "所属院系"
    //       },
    //       {
    //         name: "email",
    //         comment: "联系方式"
    //       }
    //     ],
    //     primaryKeys: ["id"],
    //     foreignKeys: [
    //       {
    //         column: "department_id",
    //         referenceTable: "Departments",
    //         referenceColumn: "id",
    //         comment: "所属院系外键"
    //       }
    //     ]
    //   },
    //   {
    //     tableName: "Departments",
    //     comment: "院系信息表",
    //     columns: [
    //       {
    //         name: "id",
    //         comment: "院系ID"
    //       },
    //       {
    //         name: "name",
    //         comment: "院系名称"
    //       },
    //       {
    //         name: "location",
    //         comment: "院系位置"
    //       },
    //       {
    //         name: "dean_id",
    //         comment: "院长ID"
    //       }
    //     ],
    //     primaryKeys: ["id"],
    //     foreignKeys: [
    //       {
    //         column: "dean_id",
    //         referenceTable: "Teachers",
    //         referenceColumn: "id",
    //         comment: "院长外键"
    //       }
    //     ]
    //   }
    // ];
    // console.log(resultData);
    // erDiagram.value.updateDiagram(resultData, layoutType.value);
    // // setLayoutType(layoutType.value);
    // ElMessage.success("ER图生成成功");
    // // 同步右侧颜色选择器和实体列表
    // nextTick(() => {
    //   nodeColor.value = erDiagram.value?.getCurrentNodeColor() || "#000000";
    //   lineColor.value = erDiagram.value?.getCurrentLineColor() || "#000000";
    //   entityList.value = erDiagram.value?.getEntityList() || [];
    // });
    // } else {
    //   console.error("SQL解析失败:", parseResult.error);
    //   ElMessage.error(parseResult.error || "SQL格式有误，请检查语法");
    // }

    // 注释掉原来的模拟数据代码
    /*
    // 模拟后端返回的数据 - 用于测试
    const mockResponseData = [
      // ... 原来的模拟数据 ...
    ];

    // 使用模拟数据而不是发送请求到后端
    console.log("使用模拟数据:", mockResponseData);

    if (
      mockResponseData &&
      Array.isArray(mockResponseData) &&
      mockResponseData.length > 0
    ) {
      erDiagram.value.updateDiagram(mockResponseData);
      ElMessage.success("ER图生成成功");
    } else {
      ElMessage.warning("未能识别有效的建表语句，请检查SQL语法");
    }
    */

    // 注释掉原来的后端请求代码
    /*
    // 发送原始SQL语句到服务器
    const response = await axios.post('http://localhost:8080/api/er-diagram/parse',
      { sql },
      {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        withCredentials: true
      }
    )

    // 打印后端返回的数据
    console.log('后端返回的数据:', response.data)

    if (response.data && Array.isArray(response.data) && response.data.length > 0) {
      erDiagram.value.updateDiagram(response.data)
      ElMessage.success('ER图生成成功')
    } else {
      ElMessage.warning('未能识别有效的建表语句，请检查SQL语法')
    }
    */
  } catch (error) {
    console.error("完整错误信息:", error);
    ElMessage.error("SQL解析失败，请检查语法格式");
  }
};

const generateFromAI = () => {
  if (!aiInput.value.trim()) {
    ElMessage.warning("请输入系统描述");
    return;
  }
  // ElMessage.success("正在使用AI生成ER图...");
  startSSE(aiInput.value);
  // 这里可以实现AI生成逻辑
};

const saveFile = () => {
  ElMessage.success("文件保存成功");
};

const exportFile = () => {
  ElMessage.success("导出成功");
};

const fitToScreen = () => {
  ElMessage.info("适应屏幕");
};

const resetView = () => {
  zoomLevel.value = 100;
  ElMessage.info("视图已重置");
};

const centerView = () => {
  ElMessage.info("视图已居中");
};

const handleExportDiagram = diagram => {
  // 处理导出逻辑
  const dataUrl = diagram.makeImageData({
    scale: 1,
    background: "white"
  });

  const link = document.createElement("a");
  link.download = "er-diagram.png";
  link.href = dataUrl;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const selectEntity = (entity: any) => {
  // 清除其他选择
  entities.value.forEach(e => (e.selected = false));
  relationships.value.forEach(r => (r.selected = false));

  entity.selected = true;
  selectedNodeName.value = entity.name;
};

const selectRelationship = (relationship: any) => {
  // 清除其他选择
  entities.value.forEach(e => (e.selected = false));
  relationships.value.forEach(r => (r.selected = false));

  relationship.selected = true;
  selectedNodeName.value = relationship.name;
};

const handleCanvasClick = (event: MouseEvent) => {
  // 点击空白区域取消选择
  if (event.target === event.currentTarget) {
    entities.value.forEach(e => (e.selected = false));
    relationships.value.forEach(r => (r.selected = false));
  }
};

const startDrag = (item: any, event: MouseEvent) => {
  isDragging.value = true;
  dragTarget.value = item;

  const rect = canvasContainer.value.getBoundingClientRect();
  dragOffset.x = event.clientX - rect.left - item.x;
  dragOffset.y = event.clientY - rect.top - item.y;

  event.preventDefault();
};

const handleMouseDown = (event: MouseEvent) => {
  // 处理鼠标按下事件
};

const handleMouseMove = (event: MouseEvent) => {
  if (isDragging.value && dragTarget.value) {
    const rect = canvasContainer.value.getBoundingClientRect();
    dragTarget.value.x = event.clientX - rect.left - dragOffset.x;
    dragTarget.value.y = event.clientY - rect.top - dragOffset.y;
  }
};

const handleMouseUp = () => {
  isDragging.value = false;
  dragTarget.value = null;
};

const updateNodeName = () => {
  const selected = [...entities.value, ...relationships.value].find(
    item => item.selected
  );
  if (selected) {
    selected.name = selectedNodeName.value;
    ElMessage.success("节点名称已更新");
  }
};

const deleteNode = () => {
  const entityIndex = entities.value.findIndex(e => e.selected);
  const relationshipIndex = relationships.value.findIndex(r => r.selected);

  if (entityIndex !== -1) {
    entities.value.splice(entityIndex, 1);
    ElMessage.success("实体已删除");
  } else if (relationshipIndex !== -1) {
    relationships.value.splice(relationshipIndex, 1);
    ElMessage.success("关系已删除");
  }
};

const addConnection = () => {
  if (!newConnectionName.value.trim()) {
    ElMessage.warning("请输入名称");
    return;
  }

  ElMessage.success(
    `已添加${newConnectionType.value}: ${newConnectionName.value}`
  );
  newConnectionName.value = "";
};

const handleExampleDialogClose = () => {
  showExampleDialog.value = false;
};

const useExample = () => {
  if (leftActiveTab.value === "sql") {
    sqlInput.value = exampleSQL;
  }
  showExampleDialog.value = false;
  ElMessage.success("示例已加载");
};

const handleFontUpload = (file: File) => {
  addFontForm.file = file;
  addFontForm.fileName = file.name;
  return false; // 阻止自动上传
};
const handleAddFont = () => {
  // 占位：添加字体逻辑
  showAddFontDialog.value = false;
  ElMessage.success("添加字体（占位）");
};

const dragNodeType = ref(null);
const onDragStart = (type, e) => {
  dragNodeType.value = type;
  e.dataTransfer.setData("nodeType", type);
};
const onDropOnCanvas = e => {
  e.preventDefault();
  const type = e.dataTransfer.getData("nodeType") || dragNodeType.value;
  if (!type) return;
  const diagramDiv = document.querySelector(".diagram-container");
  if (!diagramDiv) return;
  const rect = diagramDiv.getBoundingClientRect();
  const pos = { x: e.clientX - rect.left, y: e.clientY - rect.top };
  erDiagram.value?.addNode(type, pos);
  dragNodeType.value = null;
};

onMounted(() => {
  // 初始化画布
});

watch(selectedNodeName, val => {
  if (selectedNode.value && val !== selectedNode.value.name) {
    console.log(val);
    erDiagram.value?.updateNodeName(selectedNode.value.key, val);
    // 不要刷新selectedNode.value，否则输入框会失焦
  }
});
</script>

<style scoped>
/* Web3 风格样式 */
.web3-tabs {
  --el-color-primary: #06b6d4;
  --el-color-primary-light-3: #0891b2;
  --el-color-primary-light-5: #0e7490;
  --el-color-primary-light-7: #155e75;
  --el-color-primary-light-8: #164e63;
  --el-color-primary-light-9: #0c4a6e;
  --el-color-primary-dark-2: #0891b2;
}

.web3-tabs :deep(.el-tabs__header) {
  background: rgba(30, 41, 59, 0.5);
  backdrop-filter: blur(12px);
  border-bottom: 1px solid rgba(6, 182, 212, 0.2);
  margin: 0;
}

.web3-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.web3-tabs :deep(.el-tabs__item) {
  color: #94a3b8;
  font-weight: 500;
  transition: all 0.3s ease;
}

.web3-tabs :deep(.el-tabs__item:hover) {
  color: #06b6d4;
}

.web3-tabs :deep(.el-tabs__item.is-active) {
  color: #06b6d4;
  background: rgba(6, 182, 212, 0.1);
}

.web3-tabs :deep(.el-tabs__active-bar) {
  background: linear-gradient(90deg, #06b6d4, #ec4899);
  height: 3px;
}

.web3-textarea :deep(.el-textarea__inner) {
  background: rgba(30, 41, 59, 0.5);
  border: 1px solid rgba(100, 116, 139, 0.3);
  color: #f1f5f9;
  border-radius: 8px;
  backdrop-filter: blur(8px);
  transition: all 0.3s ease;
}

.web3-textarea :deep(.el-textarea__inner):focus {
  border-color: #06b6d4;
  box-shadow: 0 0 0 2px rgba(6, 182, 212, 0.2);
}

.web3-select :deep(.el-input__wrapper) {
  background: rgba(30, 41, 59, 0.5);
  border: 1px solid rgba(100, 116, 139, 0.3);
  border-radius: 8px;
  backdrop-filter: blur(8px);
  transition: all 0.3s ease;
}

.web3-select :deep(.el-input__wrapper):hover {
  border-color: #06b6d4;
}

.web3-select :deep(.el-input__wrapper.is-focus) {
  border-color: #06b6d4;
  box-shadow: 0 0 0 2px rgba(6, 182, 212, 0.2);
}

.web3-select :deep(.el-input__inner) {
  color: #f1f5f9;
}

.web3-input :deep(.el-input__wrapper) {
  background: rgba(30, 41, 59, 0.5);
  border: 1px solid rgba(100, 116, 139, 0.3);
  border-radius: 8px;
  backdrop-filter: blur(8px);
  transition: all 0.3s ease;
}

.web3-input :deep(.el-input__wrapper):hover {
  border-color: #06b6d4;
}

.web3-input :deep(.el-input__wrapper.is-focus) {
  border-color: #06b6d4;
  box-shadow: 0 0 0 2px rgba(6, 182, 212, 0.2);
}

.web3-input :deep(.el-input__inner) {
  color: #f1f5f9;
}

.web3-button-primary {
  background: linear-gradient(135deg, #06b6d4, #ec4899);
  border: none;
  color: white;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(6, 182, 212, 0.3);
}

.web3-button-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(6, 182, 212, 0.4);
}

.web3-button-secondary {
  background: rgba(30, 41, 59, 0.8);
  border: 1px solid rgba(6, 182, 212, 0.3);
  color: #06b6d4;
  font-weight: 500;
  border-radius: 8px;
  backdrop-filter: blur(8px);
  transition: all 0.3s ease;
}

.web3-button-secondary:hover {
  background: rgba(6, 182, 212, 0.1);
  border-color: #06b6d4;
  transform: translateY(-1px);
}

.web3-button-gradient {
  background: linear-gradient(135deg, #8b5cf6, #06b6d4);
  border: none;
  color: white;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.web3-button-gradient:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(139, 92, 246, 0.3);
}

.web3-button-tool {
  background: rgba(30, 41, 59, 0.6);
  border: 1px solid rgba(100, 116, 139, 0.3);
  color: #94a3b8;
  font-size: 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.web3-button-tool:hover {
  background: rgba(6, 182, 212, 0.1);
  border-color: #06b6d4;
  color: #06b6d4;
}

.web3-button-active {
  background: linear-gradient(135deg, #8b5cf6, #ec4899);
  border: none;
  color: white;
  font-weight: 600;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
}

.web3-button-inactive {
  background: rgba(30, 41, 59, 0.6);
  border: 1px solid rgba(139, 92, 246, 0.3);
  color: #a78bfa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.web3-button-inactive:hover {
  background: rgba(139, 92, 246, 0.1);
  border-color: #8b5cf6;
}

.web3-color-picker :deep(.el-color-picker__trigger) {
  border: 1px solid rgba(100, 116, 139, 0.3);
  border-radius: 6px;
  transition: all 0.3s ease;
}

.web3-color-picker :deep(.el-color-picker__trigger):hover {
  border-color: #06b6d4;
}

.web3-dialog :deep(.el-dialog) {
  background: rgba(30, 41, 59, 0.95);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(6, 182, 212, 0.2);
  border-radius: 16px;
}

.web3-dialog :deep(.el-dialog__header) {
  background: rgba(6, 182, 212, 0.1);
  border-bottom: 1px solid rgba(6, 182, 212, 0.2);
  border-radius: 16px 16px 0 0;
}

.web3-dialog :deep(.el-dialog__title) {
  color: #f1f5f9;
  font-weight: 600;
}

.web3-dialog :deep(.el-dialog__body) {
  color: #94a3b8;
}

/* 滚动条样式 */
:deep(::-webkit-scrollbar) {
  width: 6px;
}

:deep(::-webkit-scrollbar-track) {
  background: rgba(30, 41, 59, 0.3);
  border-radius: 3px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: rgba(6, 182, 212, 0.5);
  border-radius: 3px;
}

:deep(::-webkit-scrollbar-thumb):hover {
  background: rgba(6, 182, 212, 0.7);
}
</style>
